package com.mianyang.zhangsan.common.util;

import com.mianyang.zhangsan.exception.SecServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

/**
 * 文件工具类
 * @author jiangjr
 * @date 2022-10-26
 */
@Slf4j
public class FileUtils {
    private final static String DEFAULT_PATH = "D:\\我的\\绵阳师范学院\\毕业设计\\temp\\";

    /**
     * 文件转化
     * @return 文件路径
     */
    public static String convert2File(MultipartFile file) {
        String filePath = DEFAULT_PATH + UUID.randomUUID() + file.getOriginalFilename();
        File local = new File(filePath);
        try {
            file.transferTo(local);
        } catch (IOException e) {
            log.error("文件转化异常");
            throw new RuntimeException("文件转化异常");
        }
        return filePath;
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     */
    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            if (!file.delete()) {
                log.error("文件转化产生的临时文件未删除");
            }
        }
    }

    /**
     * 读取本地文件为MultipartFile
     * @param filePath 文件路径
     * @return MultipartFile
     */
    public static MultipartFile readSystemFile(String filePath) {
        File file = new File(filePath);
        FileInputStream in = null;
        MultipartFile multipartFile = null;
        if (file.exists()) {
            try {
                in = new FileInputStream(file);
                multipartFile = convertToMultipartFile(in, file.getName());
            } catch (IOException e) {
                // 异常处理
                log.error("本地文件读取转化异常-{}", e.getMessage());
                throw new RuntimeException("本地文件读取转化异常");
            }finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    // 输入流关闭异常
                    log.error("输入流关闭异常-{}", e.getMessage());
                }
            }
        }
        return multipartFile;
    }

    public static MultipartFile readMultipartFile(OutputStream out, String filename) {
        InputStream in = null;
        MultipartFile multipartFile = null;
        try {
            if (out instanceof ByteArrayOutputStream) {
                InputStreamSource resource = new ByteArrayResource(((ByteArrayOutputStream)out).toByteArray());
                in = resource.getInputStream();
            }
            if (in != null) {
                multipartFile = new MockMultipartFile(filename, filename,
                        ContentType.APPLICATION_OCTET_STREAM.toString(), in);
            }
        } catch (IOException e) {
            // 异常处理
            log.error("文件转化异常-{}", e.getMessage());
            throw new SecServiceException("文件转化异常");
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                // 输入流关闭异常
                log.error("文件流关闭异常");
            }
        }
        return multipartFile;
    }

    public static MultipartFile convertToMultipartFile(InputStream in, String fileName) {
        try {
            return new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), in);
        } catch (IOException e) {
            log.error("文件转换异常-{}", e.getMessage());
            throw new SecServiceException("文件转换异常");
        }

    }

    public static InputStream readWebFile(String url) {
        InputStream in;
        try {
            URL source = new URL(url);
            URLConnection connection = source.openConnection();
            connection.connect();
            HttpURLConnection httpConnect = (HttpURLConnection) connection;
            if (httpConnect.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.error("网络文件读取返回值异常");
                throw new SecServiceException("网络文件读取返回值异常");
            }
            in = httpConnect.getInputStream();
        } catch (IOException e) {
            log.error("网络文件读取异常-{}", e.getMessage());
            throw new SecServiceException("网络文件读取异常");
        }
        return in;
    }

    public static void convert2Out(InputStream in, OutputStream out) {
        try {
            byte[] buff = new byte[1024 * 1024];
            int len = 0;
            while ((len = in.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } catch (IOException e) {
            log.error("文件处理异常-流转换异常-{}", e.getMessage());
            throw new RuntimeException("文件处理异常-流转换异常");
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("文件流关闭异常");
            }
        }
    }
}
